package Service;

import Entity.User;
import GUI.MainFrame;
import Monitor.ClientThread;
import Utils.PacketUtils;
import Utils.ReceiveObject;
import Utils.ThreadManage;
import org.json.JSONObject;

import java.io.*;
import java.util.HashMap;

/**
 * The type Request fri status.
 *
 * @author dzr
 * @version 1.0
 */
public class RequestFriStatus {
    /**
     * The constant ASK_FRI_INFO.
     */
    public static final int ASK_FRI_INFO = 5;

    /**
     * Request friend's information.
     *
     * @param uid the uid
     */
    public static void requestFriInfo(int uid){
        JSONObject ret2Server = new JSONObject();
        ret2Server.put("uid", uid);
        ret2Server.put("cmd", ASK_FRI_INFO);
        PacketUtils.sendPacket(ret2Server);

        ClientThread clientThread = ThreadManage.getInstance().getClientThreads().get(uid);

        Object data;
        try {
            data = ReceiveObject.receiveObject(clientThread.getSocket());
            if(data instanceof HashMap){
                HashMap<Integer, User> friends_online = (HashMap<Integer, User>) data;
                clientThread.setFriends_online(friends_online);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Add new online friend.
     *
     * @param uid the my uid
     * @throws IOException the io exception
     */
    public static void addFriOnline(int uid) throws IOException {
        ClientThread clientThread = ThreadManage.getInstance().getClientThreads().get(uid);

        Object data = ReceiveObject.receiveObject(clientThread.getSocket());
        if(data instanceof User){
            User newFriOnline = (User) data;
            clientThread.getFriends_online().put(newFriOnline.getUid(), newFriOnline);
            clientThread.getMainFrame().updateFriendStatus(newFriOnline, true, true);
        }
    }

    /**
     * Delete outline friend.
     *
     * @param uid the my uid
     * @throws IOException the io exception
     */
    public static void delFriOutline(int uid) throws IOException {
        ClientThread clientThread = ThreadManage.getInstance().getClientThreads().get(uid);

        Object data = ReceiveObject.receiveObject(clientThread.getSocket());
        if(data instanceof User){
            User newFriOnline = (User) data;
            clientThread.getFriends_online().remove(newFriOnline.getUid());
            clientThread.getMainFrame().updateFriendStatus(newFriOnline, false, true);
        }
    }
}
